import { NativeServiceProvider } from './../../providers/native-service/native-service';
import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams,Platform } from 'ionic-angular';

/**
 * Generated class for the BaiduMapPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
declare var BMap;
declare var BMAP_ANCHOR_TOP_LEFT;
declare var BMAP_NORMAL_MAP;
declare var BMAP_HYBRID_MAP;
@IonicPage()
@Component({
  selector: 'page-baidu-map',
  templateUrl: 'baidu-map.html',
})
export class BaiduMapPage {
  @ViewChild('map') map_container: ElementRef;

  map: any;//地图对象
  marker: any;//标记
  myIcon: any;
  lat =  30.52; //默认位置
  lon = 114.38;//默认位置

  address = "";

  constructor(public navCtrl: NavController, public navParams: NavParams
    ,public nativeService: NativeServiceProvider,
    public platform: Platform,
    ) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad BaiduMapPage');
    this.map = new BMap.Map(this.map_container.nativeElement);

    this.lat = this.nativeService.lat == -1 ? 30.52 : this.nativeService.lat;
    this.lon = this.nativeService.lon == -1 ? 114.38 : this.nativeService.lon;

    let point = new BMap.Point(this.lon, this.lat);
    // 设置初始显示中心和地图级别，最小为1，最大是17级，地图级别越大放大程度越大
    // 只有在地图初始化后才可以进行其他操作
    this.map.centerAndZoom(point, 14);
    //允许使用滚轮放大缩小，默认禁用
    this.map.enableScrollWheelZoom(true);
    this.map.addControl(new BMap.ScaleControl({ offset: new BMap.Size(5, 5), anchor: BMAP_ANCHOR_TOP_LEFT }));
    this.map.addControl(new BMap.MapTypeControl({
      mapTypes:[
              BMAP_NORMAL_MAP,
              BMAP_HYBRID_MAP
          ]}));
    console.log('begin to platform ready');
    this.platform.ready().then(() => {
      console.log('this platform is ready')
      if (this.nativeService.lat == -1) {
              //如果一开始没有获取到全局经纬度
              setTimeout(() => {
                this.moveToCurrentPosition();
              }, 10);
      }
    })
  }


  moveToCurrentPosition() {
    console.log('Move to current location')
    this.nativeService.getCurrentPosition().then((data) => {
      if (this.nativeService.isIos()) {
        //通过百度地图的Convertor类转为百度地图坐标
        var convertor = new BMap.Convertor();
        var pointArr = [];
        let mpoint = new BMap.Point(data.lon, data.lat);
        pointArr.push(mpoint);
        convertor.translate(pointArr, 1, 5, (data) => {
          if (data.status === 0) {
            let mIcon = new BMap.Icon("assets/imgs/map_pin.png", new BMap.Size(40, 40), { anchor: new BMap.Size(15, 32) });
            var marker = new BMap.Marker(data.points[0], { icon: mIcon });
            let geocoder = new BMap.Geocoder();
            geocoder.getLocation(data.points[0], (result) => {
              this.address = result['address'];
            });
            this.map.addOverlay(marker);
            this.map.setCenter(data.points[0]);
            this.lat = data.points[0].lat;
            this.lon = data.points[0].lng;
            this.nativeService.lat = this.lat;
            this.nativeService.lon = this.lon;
          }
        });
        // this.map.panTo(mpoint);
        console.log("当前地址：" + data.lon + "    " + data.lat);
        this.nativeService.hideLoading();
      } else {
        console.log(JSON.stringify(data))
        let mpoint = new BMap.Point(data.lon, data.lat);
        let mIcon = new BMap.Icon("assets/imgs/map_pin.png", new BMap.Size(40, 40), { anchor: new BMap.Size(15, 32) });
        var marker = new BMap.Marker(mpoint, { icon: mIcon });
        let geocoder = new BMap.Geocoder();
        geocoder.getLocation(new BMap.Point(data.lon, data.lat), (result) => {
          // {"point":{"lng":122,"lat":32},"address":"江苏省无锡市江阴市","addressComponents":{"streetNumber":"","street":"","district":"江阴市","city":"无锡市","province":"江苏省"},"surroundingPois":[],"business":""}
          this.address = result['address'];
        });
        this.map.addOverlay(marker);
        this.map.setCenter(mpoint);
        this.lat = data.lat;
        this.lon = data.lon;
        this.nativeService.lat = this.lat;
        this.nativeService.lon = this.lon;
        console.log("修正的百度定位地址", data.lat + "  " + data.lon);
        this.nativeService.hideLoading();
      }
    }).catch((error) => {
      console.log("查看错误", error);
      this.nativeService.hideLoading();
      this.nativeService.showToast("无法定位到当前位置，可能是手机定位没有开启或者应用没有定位权限", 3000);
    });
  }

}
